<template>
    <div class="w-full">
        <!-- 导航栏 -->
        <nav class="mb-5 flex justify-center">
            <ul class="w-[35rem] flex rounded-full bg-[var(--inputBg)] justify-between">
                <li class="active conNav" @click="getNavEl">
                    个性推荐</li>
                <li class="conNav" @click="getNavEl">
                    专属定制</li>
                <li class="conNav" @click="getNavEl">
                    歌单</li>
                <li class="conNav" @click="getNavEl">
                    排行榜</li>
                <li class="conNav" @click="getNavEl">
                    歌手</li>
                <li class="conNav" @click="getNavEl">
                    最新音乐</li>
            </ul>
        </nav>
        <!-- 轮播图 -->
        <Banner></Banner>
        <h1 id="actorRecom" class="cardTitle">🎉人气声优</h1>
        <!-- 达人推荐 -->
        <div v-if="recommendVoiceActorList.length !== 0" class="flex justify-between">
            <div class="flex flex-wrap justify-center gap-x-6 gap-y-3">
                <CardTransition :ref="el=>{refList[index] = el}" @click="openCard(item,index)"
                    v-for="(item, index) in recommendVoiceActorList" :key="index">
                    <template #default>
                        <div
                            class="bg-[var(--inputBg)] hover:bg-[var(--active)] w-auto rounded-lg flex overflow-hidden pt-1 pl-3 pr-1 pb-1 transform transition-transform duration-300 hover:scale-105">
                            <div class="flex flex-col  max-w-[7rem] w-[7rem]">
                                <div class="font-black text-lg truncate">{{ item.username }}</div>
                                <div class="font-normal text-xs line-clamp-1">{{ item.intro }}</div>
                                <img class="h-20 object-cover rounded-full w-20" :src="item.avatar">
                            </div>
                            <div class="rounded-lg p-4">
                                <div class="flex justify-between">
                                    <div :class="['rounded-lg flex flex-col', index === 1 ? 'ml-2' : '']"
                                        v-for="(item1, index) in item.voicePackageList.slice(0,2)">
                                        <img class="object-cover h-20 w-20 rounded-lg" :src="item1.avatar" alt="">
                                        <div class="font-black text-sm text-center mt-1 truncate max-w-[5rem]">{{
                                            item1.name }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                    <template #expanded>
                        <div v-if="voiceActorInfo.uid" class="relative p-6 mx-auto">
                            <div class="absolute top-4 right-4 cursor-pointer text-gray-400 hover:text-gray-600"
                                @click.stop="closeCard(index)">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                    stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </div>
                            <div class="flex items-center gap-6 mb-6">
                                <img class="h-24 w-24 rounded-full object-cover shadow-md" :src="voiceActorInfo.avatar"
                                    alt="avatar">
                                <div>
                                    <div class="font-extrabold text-xl text-gray-900 flex items-center gap-2">
                                        {{ voiceActorInfo.username }}
                                        <span class="text-sm text-gray-500">{{ voiceActorInfo.gender }}</span>
                                    </div>
                                    <div class="text-sm text-gray-600 mt-2">{{ voiceActorInfo.intro || "这个人很懒，没留下什么" }}
                                    </div>
                                    <!-- <div class="text-sm text-gray-500 mt-1">签名: {{ voiceActorInfo.voiceSign || "暂无签名" }}</div> -->
                                    <div v-if="voiceActorInfo.voiceSign" class="mt-2">
                                        <VoiceSignCard :voiceSign="voiceActorInfo.voiceSign" />
                                    </div>
                                </div>
                            </div>
                            <h1 class="text-1xl font-bold text-[var(--text)] mb-2">🎇作品集</h1>
                            <!-- Voice Package List -->
                            <div class="grid grid-cols-6 gap-3">
                                <div class="flex flex-col items-center relative"
                                    v-for="(item1, index) in voiceActorInfo.voicePackageList" :key="index">
                                    <!-- 头像 -->
                                    <div class="relative">
                                        <img class="h-20 w-20 rounded-lg object-cover shadow-md" :src="item1.avatar"
                                            alt="voice package avatar">
                                        <!-- 播放量 -->
                                        <div
                                            class="absolute top-0 right-0 bg-black/60 text-white text-xs rounded-full px-2 py-1 flex items-center gap-1 shadow-md">
                                            <el-icon size="12" class="text-gray-200">
                                                <Headset />
                                            </el-icon>
                                            <span>{{ $utils.formatPlayCount(item1.playCount) }}</span>
                                        </div>
                                    </div>

                                    <!-- 名字 -->
                                    <div class="font-medium text-sm mt-1 truncate text-center text-gray-800">
                                        {{ item1.name }}
                                    </div>

                                    <!-- 更新时间 -->
                                    <div class="text-xs text-gray-400 mt-1">
                                        {{ $utils.formatUpdateTime(item1.updateTime) }}更新
                                    </div>
                                </div>
                            </div>

                        </div>
                    </template>
                </CardTransition>
            </div>
        </div>
        <!-- 数据加载中显示骨架屏 -->
        <div v-else class="flex flex-wrap  gap-6">
            <el-skeleton class="max-w-[30%]" animated :rows="4" :loading="recommendVoiceActorList.length === 0"
                v-for="index in 6" :key="index">
                <template #template>
                    <div class="bg-gray-100 h-44 rounded-lg flex flex-col justify-between p-4 shadow-md">
                        <!-- 用户头像骨架 -->
                        <div class="flex items-center">
                            <el-skeleton-item variant="circle" class="w-20 h-20" />
                            <div class="ml-4 flex flex-col">
                                <el-skeleton-item variant="text" class="w-24 h-4 mb-2" />
                                <el-skeleton-item variant="text" class="w-16 h-3" />
                            </div>
                        </div>
                        <!-- 内容骨架 -->
                        <div class="flex justify-between">
                            <el-skeleton-item v-for="item in 3" :key="item" variant="rect"
                                class="w-20 h-20 rounded-lg" />
                        </div>
                    </div>
                </template>
            </el-skeleton>
        </div>
        <!-- 推荐语音包 -->
        <div class="flex justify-between items-center mb-2">
            <h1 id="packageRecom" class="cardTitle">✨推荐语音包</h1>
            <button
                class="text-[var(--primary)] border border-[var(--primary)] px-4 py-2 rounded-full transition duration-300"
                @click="fetchNextPage">
                换一批
            </button>
        </div>
        <ul class="grid grid-cols-5 gap-3">
            <el-skeleton v-for="_ in 10" :loading="recomVoicePackageList.length === 0" animated>
                <template #template>
                    <el-skeleton-item variant="image" style="width: 195.7px; height: 180px" />
                    <div style="padding: 14px">
                        <el-skeleton-item variant="h3" style="width: 50%" />
                        <div style="display: flex;align-items: center;justify-items: space-between;margin-top: 16px;height: 16px;">
                            <el-skeleton-item variant="text" style="margin-right: 16px" />
                            <el-skeleton-item variant="text" style="width: 30%" />
                        </div>
                    </div>
                </template>
            </el-skeleton>
            <li v-for="item in recomVoicePackageList" :key="item.id" @click="goToVoicePackageDetail(item.id)"
                class="p-4 rounded-lg flex flex-col items-center group hover:bg-[var(--active)] bg-[var(--inputBg)] hover:cursor-pointer duration-300">
                <!-- 图片区域 -->
                <div class="relative mb-2 group/item overflow-hidden">
                    <div
                        class="bg-gray-800 w-full text-[var(--contentBg)] px-2 py-1 opacity-80 rounded-t-lg absolute line-clamp-2 text-ellipsis h-12 text-sm translate-y-[-100%] group-hover/item:translate-y-0 duration-500">
                        {{ item.name }}</div>
                    <img loading="lazy" class="rounded-lg object-cover w-52 h-48" :src="item.avatar" />
                    <!-- 播放计数 -->
                    <div
                        class="absolute top-2 right-2 bg-black/60 text-white text-xs rounded-full px-2 py-1 flex items-center gap-1 shadow-md">
                        <el-icon size="17" class="text-gray-200">
                            <Headset />
                        </el-icon>
                        <span class="text-gray-200 text-base">
                            {{ $utils.formatPlayCount(item.playCount) }}
                        </span>
                    </div>
                    <!-- 播放图标 -->
                    <i
                        class="iconfont icon-bofang invisible group-hover:visible text-[var(--playBg)] before:text-[40px] absolute right-3 top-[60%] font-bold hover:scale-125 transition-all"></i>
                </div>
                <div class="w-full text-center">
                    <p class="text-[var(--text)] line-clamp-1 text-ellipsis mb-2">
                        {{ item.name }}
                    </p>
                    <!-- 用户信息区域 -->
                    <div class="flex items-center gap-3">
                        <!-- 用户头像 -->
                        <img class="w-10 h-10 rounded-full object-cover border border-gray-300 shadow"
                            :src="item.userInfo.avatar" alt="User Avatar" />
                        <!-- 用户名和更新时间 -->
                        <div class="flex flex-col text-left">
                            <span class="text-sm text-[var(--text)] font-medium">
                                {{ item.userInfo.username }}
                            </span>
                            <span class="text-xs text-gray-400">
                                上次更新于{{ $utils.formatUpdateTime(item.updateTime) }}
                            </span>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
    </div>
</template>
<script setup lang='ts'>
    import { onMounted, ref, watchEffect, nextTick, getCurrentInstance } from 'vue'
    import { setVNumber, setTime, setDuration } from '@renderer/hooks'
    import { useRouter } from 'vue-router'
    import { useStore } from '@renderer/store'
    import { storeToRefs } from 'pinia'
    import CardTransition from "@renderer/components/CardTransition.vue";
    import { Headset } from '@element-plus/icons-vue'
    const { proxy } = getCurrentInstance();
    const router = useRouter()

    const { voice } = useStore()
    /**
     * 声优数据
    **/
    const recomActorLoad = ref(true)
    const { recommendVoiceActorList } = storeToRefs(voice)
    const { voiceActorInfo } = storeToRefs(voice)
    const refList = ref([]); //所有OpenContainer的ref

    /**
     * 语音包数据
    **/
    const recomPackLoad = ref(true) //是否加载中
    const currentPage = ref(1); // 当前页码
    const lastPage = ref(1); // 最后一页
    const { recomVoicePackageList } = storeToRefs(voice)


    onMounted(() => {
        const recommendVoiceActorListObserver = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    getRecommendActor()
                }
            });
        });
        const recommendVoicePackageListObserver = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    getRecommendPackage(1)
                    recommendVoicePackageListObserver.disconnect();
                }
            });
        });
        recommendVoiceActorListObserver.observe(document.getElementById('actorRecom') as HTMLElement);
        recommendVoicePackageListObserver.observe(document.getElementById('packageRecom') as HTMLElement);
    })


    watchEffect(() => {
        if (recommendVoiceActorList.value.length !== 0) {
            recomActorLoad.value = false
        }
        if (recomVoicePackageList.value.length !== 0) {
            recomPackLoad.value = false
        }
    })

    const getRecommendPackage = async (page) => {
        if (page > lastPage.value) return; // 如果已经加载到最后一页，直接返回
        recomPackLoad.value = true; // 设置加载中状态
        const response = await voice.getVoicePackageList(page); // 后端请求
        if (response) {
            recomVoicePackageList.value = response.data;
            currentPage.value = response.current_page;
            lastPage.value = response.total;
        }
        recomPackLoad.value = false; // 加载完成
    };

    // 换一批按钮触发
    const fetchNextPage = () => {
        currentPage.value = currentPage.value >= lastPage.value ? 1 : currentPage.value + 1; // 循环回到第一页
        getRecommendPackage(currentPage.value);
    };

    // 获取推荐声优
    const getRecommendActor = proxy?.$utils.debounce(async () => {
        if (recommendVoiceActorList.value.length == 0) {
            await voice.homeRecommendVoiceActor()
        }
    }, 500)

    // 获取声优详情
    const getActorDetail = proxy?.$utils.debounce(async (id) => {
        await voice.getVoiceActorDetail(id)
    }, 500)

    const openCard = proxy?.$utils.debounce(async (item, index) => {
        await getActorDetail(item.uid)
        nextTick(() => {
            let refItem = refList.value[index]
            refItem.handleCardClick()
        })
    }, 500)

    const closeCard = proxy?.$utils.throttle(async (index) => {
        nextTick(() => {
            let refItem = refList.value[index]
            voiceActorInfo.value = {}
            refItem.closeCard()
        })
    }, 500)

    // 跳转语音包详情页
    const goToVoicePackageDetail = (id: number | string) => {
        let scrollValue = document.querySelector('#main')?.scrollTop
        router.push({ path: '/voicePackageDetail', query: { id: id, scrollValue } })
    }

</script>
<style scoped lang='less'></style>